<!-- 填空题 -->
<template>
  <el-row>
    <!-- 题目 -->
    <el-row id="row1">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.question')">
          <richTextCom v-model="questionGroup" :group="questionGroup" @textInsertCallback="getEditorText"/>
          <!-- 说明 -->
          <div class="question-tip">* 需要学生填写的部分，请点击 “填入答案按钮“ 进行录入，录入内容即为此填空题的答案；</div>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 解析 -->
    <el-row id="row6">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.analysis')">
          <richTextCom v-model="analysisGroup" :group="analysisGroup"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 添加标签 -->
    <el-row id="row5">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.addTags')">
          <paperTagsCom ref="tags" v-model="chooseTags" :qId="qId" :show-btn="false"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 操作按钮 -->
    <div class="form-footer">
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="savePaperQuestion(1)">{{ $t('form.save') }}</el-button>
        <el-button v-if="!isEdit" type="primary" @click="savePaperQuestion(2)">{{ $t('paperQuestionLangList.goOnAddQuestion') }}</el-button>
      </el-row>
    </div>
  </el-row>
</template>

<script>
import richTextCom from './richText'
import optionChooseCom from './optionChoose'
import paperTagsCom from '../paperTags'
import { createdQuestion, getQuestionDetail, updateQuestion } from '@/api/question'
import { updatePaperQuestion } from '@/api/paper'
export default {
  name: 'Blank',
  components: {
    richTextCom,
    optionChooseCom,
    paperTagsCom
  },
  props: {
    // 试卷id
    parentPaperId: String,
    newEditType: String,
    categoryProps: {
      type: String,
      default: 'blank'
    }
  },
  data() {
    return {
      chooseOption: 4,
      // 选项个数
      optionArray: [2, 3, 4, 5, 6, 7],
      // 题目文本信息
      questionGroup: {
        category: '',
        subjectTxt: '',
        subjectAudio: ''
      },
      // 选项内容文本信息数组
      optionGroupArray: [],
      // 解析
      analysisGroup: {
        category: '',
        subjectTxt: '',
        subjectAudio: ''
      },
      // 正确答案
      answerRadio: '',
      // 选择的标签
      chooseTags: [],
      // 是否可提交标志
      submitFlag: false,
      qId: '',
      isEdit: false
    }
  },
  watch: {
    // 监听选项个数改变
    'chooseOption': function(val) {
      this.initOption()
      console.info(val)
    },
    // 监听标签选择
    'chooseTags': function(val) {
      console.info(val)
    }
  },
  created() {
    console.info(this.parentPaperId)
    this.initPage()
  },
  methods: {
    // 初始化页面
    initPage() {
      this.questionGroup.category = this.categoryProps
    },
    // 初始化数据
    initData() {
      this.questionGroup = {
        category: 'blank',
        subjectTxt: '',
        subjectAudio: ''
      }
      this.analysisGroup = {
        category: '',
        subjectTxt: '',
        subjectAudio: ''
      }
      this.chooseTags = []
      this.submitFlag = false
      this.qId = ''
      this.isEdit = false
      this.$refs.tags.initPage()
    },
    // 编辑时加载数据
    initUpdateData(row) {
      const _this = this
      _this.isEdit = true
      const loading = _this.$loading({
        lock: true,
        text: '数据加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      })
      getQuestionDetail(row.id).then(res => {
        loading.close()
        if (res) {
          res.questions.forEach(v => {
            v.option = v.options
          })
          _this.optionGroupArray = []
          _this.questionGroup.subjectTxt = res.groupSubjectTxt
          _this.questionGroup.category = res.category
          _this.questionGroup.subjectAudio = res.groupSubjectAudio
          _this.analysisGroup.subjectTxt = res.questions[0].analysisTxt
          _this.answerRadio = res.questions[0].answerKey
          _this.qId = row.id
        }
      }).catch(err => {
        loading.close()
        console.info(err)
      })
    },
    // 获取编辑中的编辑答案
    getEditorText(textVal) {
      console.info(textVal)
      const reg = /\[\[(.+?)\]\]/g
      const regVal = textVal.match(reg)
      if (regVal) {
        this.answerRadio = regVal.join(',')
      } else {
        this.answerRadio = ''
      }
      console.info(this.answerRadio)
    },
    // 表单验证
    formValidator() {
      if (this.questionGroup.subjectTxt.trim() === '') {
        this.$message({
          message: '请填写题目内容',
          type: 'warning'
        })
        document.getElementById('row1').scrollIntoView()
        return
      }
      if (this.answerRadio === '') {
        this.$message({
          message: '请填写答案',
          type: 'warning'
        })
        document.getElementById('row1').scrollIntoView()
        return
      }
      if (this.chooseTags.length === 0) {
        this.$message({
          message: '请选择至少一个标签',
          type: 'warning'
        })
        document.getElementById('row5').scrollIntoView()
        return
      }
      if (this.analysisGroup.subjectTxt.trim() === '') {
        this.$message({
          message: '请填写题目解析内容',
          type: 'warning'
        })
        document.getElementById('row6').scrollIntoView()
        return
      }
      this.submitFlag = true
    },
    // 保存
    savePaperQuestion(type) {
      const _this = this
      _this.formValidator()
      // 执行保存
      if (_this.submitFlag) {
        /* 构造FormData键值question的数据 */
        const questionOptionPostData = []
        _this.optionGroupArray.forEach(v => {
          const obj = {}
          obj.optionTxt = v.subjectTxt
          obj.optionAudio = v.subjectAudio
          obj.optionKey = v.optionKey
          questionOptionPostData.push(obj)
        })
        const questionPostData = [{
          subjectTxt: _this.questionGroup.subjectTxt,
          subjectAudio: _this.questionGroup.subjectAudio,
          analysisTxt: _this.analysisGroup.subjectTxt,
          analysisAudio: _this.analysisGroup.subjectAudio,
          answerKey: _this.answerRadio,
          option: questionOptionPostData
        }]
        /* end */
        // 提交数据
        const postData = {
          group: JSON.stringify(_this.questionGroup),
          labelIds: _this.chooseTags.join(','),
          category: _this.categoryProps,
          question: JSON.stringify(questionPostData)
        }
        const loading = _this.$loading({
          lock: true,
          text: '数据保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        // 新增
        if (!_this.isEdit) {
          createdQuestion(postData).then(res => {
            if (res) {
              if (_this.newEditType == 'question') {
                loading.close()
                // 保存
                if (type == 1) {
                  _this.$emit('saveCallback')
                }
                // 继续录题
                else if (type == 2) {
                  _this.initData()
                }
              } else {
                const questionId = res.id
                const postData2 = {
                  questionIds: questionId
                }
                // 更新试卷下的试题
                updatePaperQuestion(_this.parentPaperId, postData2).then(res => {
                  _this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  loading.close()
                  // 保存
                  if (type == 1) {
                    _this.$emit('saveCallback')
                  }
                  // 继续录题
                  else if (type == 2) {
                    _this.initData()
                  }
                }).catch(err => {
                  loading.close()
                  console.info(err)
                })
              }
            }
          }).catch(err => {
            loading.close()
            console.info(err)
          })
        }
        // 编辑
        else {
          if (_this.newEditType == 'question') {
            postData._method = 'PUT'
            updateQuestion(_this.qId, postData).then(res => {
              _this.$message({
                message: '保存成功',
                type: 'success'
              })
              loading.close()
              // 保存
              if (type == 1) {
                _this.$emit('saveCallback')
              }
              // 继续录题
              else if (type == 2) {
                _this.initData()
              }
            }).catch(err => {
              loading.close()
              console.info(err)
            })
          } else {
            postData._method = 'PUT'
            updateQuestion(_this.qId, postData).then(res => {
              if (res) {
                const questionId = res.id
                const postData2 = {
                  questionIds: questionId
                }
                // 更新试卷下的试题
                updatePaperQuestion(_this.parentPaperId, postData2).then(res => {
                  _this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  loading.close()
                  // 保存
                  if (type == 1) {
                    _this.$emit('saveCallback')
                  }
                  // 继续录题
                  else if (type == 2) {
                    _this.initData()
                  }
                }).catch(err => {
                  loading.close()
                  console.info(err)
                })
              }
            })
          }
        }
      }
    }
  }
}
</script>
